import { defineStore } from "pinia";
import { ref } from "vue";
import {
  listGodown, //获取仓库列表
  listDict, //获取字典列表
  listLocationTree, //获取库位树
} from "../../utils/api/user/userApi";

import { handleList } from "@/utils/utils";
// 用户相关 定义 Store
export const useMemberStore = defineStore(
  "member",
  () => {
    /************************ 公共变量 ********************** */
    // 存储基准IP
    let baseIP: any = ref("192.168.110.249");
    //仓库列表
    let Stashlist: any = [];
    let warehouseList: any = reactive({ Stashlist });
    // 类型列表
    let typeList: any = [];
    let TypeList: any = reactive({ typeList });
    //库位列表
    let locationList: any = [];
    let LocationList: any = reactive({ locationList });
    //默认展示仓库
    let defaultStash: any = ref("");
    const GodownCode = ref("");
    // 换页按钮
    const swiperDots = ref(true);
    /********************** 公共方法 ****************** */
    // 获取库位树
    const getLocationTree = async () => {
      const res: any = await listLocationTree({
        GodownCode: GodownCode.value,
      });
      LocationList.locationList = res.data;
      console.log("库位树", LocationList.locationList);
    };
    //物资类型
    const getGoodsTypeList = async () => {
      const res: any = await listDict({
        DictStatus: "Normal",
        DictType: "GoodsType",
      });
      TypeList.typeList = handleList(res.data, "DictCode", "DictName");
      console.log("物资类型", TypeList.typeList);
    };
    // 获取仓库列表
    const getStashlist = async () => {
      const res = await listGodown({ GodownStatus: "Normal" });
      warehouseList.Stashlist = handleList(
        res.data,
        "GodownCode",
        "GodownName"
      );
      defaultStash.value = res.data[0] || {};
      GodownCode.value = defaultStash.value.GodownCode || "";
      await getLocationTree();
      console.log("仓库列表", warehouseList.Stashlist);
    };
    //切换仓库
    const changeStash = (stash: any) => {
      GodownCode.value = stash;
    };

    // 清理会员信息，退出登录时使用
    const exitLogin = () => {};
    /************************导出 *************************** */
    // 记得 return
    return {
      baseIP, //基准IP
      exitLogin, //退出登录
      warehouseList, //仓库列表
      defaultStash, //默认展示仓库
      changeStash, //切换仓库
      GodownCode, // 仓库编码
      getStashlist,
      getGoodsTypeList, //物资类型
      TypeList, // 类型列表
      getLocationTree, //库位树
      LocationList, //库位列表
      swiperDots, // 换页按钮
    };
  },
  // TODO: 持久化
  {
    // 配置持久化
    persist: {
      // 调整为兼容多端的API
      storage: {
        setItem(key, value) {
          uni.setStorageSync(key, value);
        },
        getItem(key) {
          return uni.getStorageSync(key);
        },
      },
      paths: [
        "TypeList",
        "baseIP",
        "defaultStash",
        "GodownCode",
        "LocationList",
      ],
    },
  }
);
